﻿using Microsoft.Extensions.Configuration;
using SqlSugar;
using System.Configuration;
using System.Reflection;
using Warehouse.Domain;

namespace Warehouse.Infrastructure
{
    public class MyContext
    {
        private readonly IConfiguration _configuration;

        public MyContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 初始化 SqlSugar 客户端
        /// </summary>
        /// <param name="connStr">连接字符串名称</param>
        /// <returns>SqlSugar 客户端实例</returns>
        public ISqlSugarClient InitDBContext(string connStr)
        {
            var connectionString = _configuration.GetConnectionString(connStr);
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentNullException(nameof(connStr), "连接字符串未配置");
            }

            var dbClient = new SqlSugarClient(new ConnectionConfig()
            {
                DbType = DbType.SqlServer, // 根据你的数据库类型选择
                ConnectionString = connectionString,
                IsAutoCloseConnection = true, // 自动关闭连接
                InitKeyType = InitKeyType.Attribute, // 支持实体类中的 [SugarColumn] 特性
                ConfigureExternalServices = new ConfigureExternalServices
                {
                    EntityService = (c, p) =>
                    {
                        // 支持 string? 和 string，实体字段没有加 ? 代表建表时该字段不能为 null
                        if (p.IsPrimarykey == false && new NullabilityInfoContext().Create(c).WriteState is NullabilityState.Nullable)
                        {
                            p.IsNullable = true;
                        }
                    }
                },
                MoreSettings = new ConnMoreSettings()
                {
                    SqlServerCodeFirstNvarchar = true, // 使用 NVARCHAR 而不是 VARCHAR
                    EnableCodeFirstUpdatePrecision = true
                }
            }, db =>
            {
                // SQL 执行后打印日志
                db.Aop.OnLogExecuted = (sql, pars) =>
                {
                    Console.WriteLine(UtilMethods.GetNativeSql(sql, pars));
                };
            });

            // 创建数据库（如果不存在）
            dbClient.DbMaintenance.CreateDatabase();

            // 初始化表结构（如果表不存在则创建）
            dbClient.CodeFirst.InitTables<Warehouse.Domain.Check>();
            dbClient.CodeFirst.InitTables<logSheet>();
            dbClient.CodeFirst.InitTables<QualityResult>();
            dbClient.CodeFirst.InitTables<WarehouseCategory>();
            dbClient.CodeFirst.InitTables<WarehouseInformation>();
            return dbClient;
        }
    }
}
